#!/usr/bin/env python
# coding=utf-8
#----------------------------------------------------------------------------
# 文件名：      mysqlDB.py
# 说明：       mysql数据库操作类
#
# 作者：       xiao
#
# 创建时间：    2010-12-11
# 版权：       (c) 2010 by xiao
# 许可证：      apache license
#----------------------------------------------------------------------------

import MySQLdb as db
import MySQLdb.cursors

##
# mysql数据库操作类
##
class Mydb():
    
    def __init__(self,host='localhost', dataBase='old', user='root', passwd=''):
        self.host = host
        self.dataBase = dataBase
        self.user = user
        self.passwd = passwd
    
    # 查询
    def query(self, sql):
        self.cur.execute(sql)
        row = self.cur.fetchall()
        return row
    
    # 添加&更新
    def save(self, sql):
        try:
            self.cur.execute(sql)
            self.conn.commit()
            
        except:
            f = open("sqlErr.log", "a")
            f.write("%s\n" % sql)
            f.close()
            return True
            
    def last_id(self):
        laIds = self.query("select LAST_INSERT_ID() as laid")
        return laIds[0]['laid']
    
    # 加载数据库    
    def dbLoad(self):
        self.conn = db.connect(host=self.host, db=self.dataBase, user=self.user,passwd=self.passwd, charset="utf8")
        self.cur = self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        self.escape_string=db.escape_string
    
    # 关闭数据库
    def dbClose(self):
        self.cur.close()
        self.conn.close()
        
if __name__ == '__main__':
    
	odb =Mydb(host='localhost', dataBase='old', user='root', passwd='')
	odb.dbLoad()
	print(odb.query("SELECT `parent_id` FROM `categories` LIMIT 10"))
	odb.dbClose()
